import { BaseResponse } from '@/domain/authority/api';
import { SelectRow, Page, ResSearch, Column, ResPageList, OpButton } from '@/domain/common/types/page';
import { reactive, ref, Ref, toRaw } from 'vue';

export type apiType<T, U = {}> = {
  list: (param: Partial<Page | (Page & T) | U>) => Promise<BaseResponse<ResPageList<T>>>;
  search: ResSearch;
  add?: (param: Partial<T>) => Promise<BaseResponse<void>>;
  update?: (param: Partial<T>) => Promise<BaseResponse<void>>;
  delete?: (param: Partial<T>) => Promise<BaseResponse<void>>;
};
/**
 *  P 主键类型
 *  T 表示表格列表字段类型
 *  U 表示查询类型
 */
export type UsePageList = <P, T, U>(
  api: apiType<T, U>,
  IDString: keyof T
) => {
  IDString: keyof T;
  rowlist: Ref<Array<{ row: T; op_group: Array<OpButton> }>>;
  /**Page类型，或者表格属性+page,或者自定义参数类型 */
  searchParam: Partial<Page | Partial<T & Page> | U>;
  columnlist: Ref<Array<Partial<Column>>>;
  searchList: Ref<ResSearch>;
  paging: Ref<Page>;
  // changeState: (type: OpType, status: boolean) => void;
  // opGroupCallBack: OpGroupCallBack<T>;
  activeId: Ref<any>;
  addStatus: Ref<boolean>;
  updateStatus: Ref<boolean>;
  showStatus: Ref<boolean>;
  setSizeChange: (current: number, pageSize: number) => Promise<void>;
  selectInfo: Ref<Partial<T>>;
  loadTable: (param: Partial<T & U>) => Promise<BaseResponse<ResPageList<T>>>;
  selectRows: Ref<SelectRow<P, T>>;
  getSelectRowsCallBack: (selectKey: Array<P>, selectRow: Array<T>) => void;
  reloadList: (params: Partial<Page | Partial<T>>) => void;
  getResData: () => ResPageList<T> | null;
  tableLoading: Ref<boolean>;
};

/**
 *
 * @returns 角色增删改查hooks
 */
export const usePageList: UsePageList = <P, T, U = {}>(api: apiType<T, U>, IDString: keyof T) => {
  const resData: Ref<ResPageList<T> | null> = ref(null);
  const searchList: Ref<ResSearch> = ref([]);
  const rowlist: Ref<Array<{ row: T; op_group: Array<OpButton> }>> = ref([]);
  const columnlist: Ref<Array<Column>> = ref([]);
  const paging: Ref<Page> = ref({ page: 1, pageSize: 10 });
  const searchParam: Partial<Page | Partial<T & Page> | U> = reactive({ page: 1, pageSize: 10 });
  // table loading 状态
  const tableLoading: Ref<boolean> = ref(true);
  //列表选择
  const selectRows: Ref<SelectRow<P, T>> = ref({});

  const getSelectRowsCallBack = (selectKey: Array<P>, selectRow: Array<T>) => {
    selectRows.value = { selectKey, selectRow };
  };

  //弹窗状态
  const addStatus = ref(false);
  const updateStatus = ref(false);
  const showStatus = ref(false);
  const selectInfo: Ref<Partial<T>> = ref({});
  const activeId: Ref<any> = ref(-1);
  //加载table
  const loadTable = async (param: Partial<Page | Partial<T>>) => {
    Object.keys(param).forEach((key) => {
      searchParam[key as keyof Partial<Page | Partial<T & Page>>] = param[key as keyof Partial<Page | Partial<T & Page>>];
    });
    tableLoading.value = true;
    let res;
    try {
      res = await api.list({ ...searchParam });
    } finally {
      tableLoading.value = false;
    }
    return res;
  };
  //分页状态
  const setSizeChange = async (current: number, pageSize: number) => {
    searchParam.page = current;
    searchParam.pageSize = pageSize;
    paging.value = { page: current, pageSize: pageSize };
    const data = (await loadTable(toRaw(searchParam))).data;
    const { datas, page } = data;
    resData.value = data;
    paging.value.total = page.total;
    rowlist.value = datas;
  };

  const reloadList = async (param: Partial<Page | Partial<T>> = {}) => {
    Object.keys(param).forEach((key) => {
      if (Array.isArray(param[key])) {
        searchParam[key as keyof Partial<Page | Partial<T & Page>>] = param[key].join('|');
      } else {
        searchParam[key as keyof Partial<Page | Partial<T & Page>>] = param[key as keyof Partial<Page | Partial<T & Page>>];
      }
    });
    const data = (await loadTable(toRaw(searchParam))).data;
    resData.value = data;
    if (data) {
      const { datas, column, page, trend } = data;
      paging.value = { page: page.page, pageSize: page.pageSize, total: page.total };
      rowlist.value = datas || [];
      columnlist.value = column!;
    }
  };
  const getResData = () => {
    return resData.value;
  };
  return {
    IDString,
    rowlist,
    searchParam,
    columnlist,
    searchList,
    getResData,
    activeId,
    addStatus,
    updateStatus,
    showStatus,
    selectInfo,
    selectRows,
    paging,
    // changeState,
    // opGroupCallBack,
    setSizeChange,
    loadTable,
    getSelectRowsCallBack,
    reloadList,
    tableLoading // table loading 状态
  };
};
